package panda.client.listeners;

import panda.client.JSNI;
import panda.client.Cardpanda;
import panda.client.ui.widgets.InPlay;
import panda.client.ui.widgets.Tooltip;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.MouseListener;
import com.google.gwt.user.client.ui.Widget;

public class TooltipListener implements MouseListener {
	/* where we want the tooltip to appear in relation to the cursor */
	private static final int xTooltipOffset = 0;
	private static final int yTooltipOffset = 0;

	private final Tooltip tip = Tooltip.get();

	public void onMouseDown(Widget source, int x, int y) {
		Tooltip.get().fadeOutTooltip(100);
	}

	/**
	 * Moves the tooltip with the mouse cursor. Takes window scrolling coordinates into account.
	 */
	public void onMouseMove(Widget source, int x, int y) {
		int scrollY = JSNI.getScrollY();
		int scrollX = JSNI.getScrollX();
		int xTooltipPosition = x + source.getAbsoluteLeft() + scrollX + xTooltipOffset;
		int yTooltipPosition = y + source.getAbsoluteTop() + scrollY + yTooltipOffset;
		Cardpanda.canvas.setWidgetPosition(tip, xTooltipPosition, yTooltipPosition);
	}

	public void onMouseUp(Widget source, int x, int y) {
		InPlay target = (InPlay) source;
		showTooltip(target.getName());
	}

	/**
	 * Unhides tooltip and fades it in. Needs to watch if the card is dragging because fast dragging causes lots of
	 * sequential onMouseEnter and onMouseLeave events.<br>
	 * TODO: remove feature 'holding shift during onmouseenter also displays imgUrl in tooltip'
	 */
	public void onMouseEnter(Widget source) {
		InPlay target = (InPlay) source;

		if(!target.isDragging()) {
			if(PandaKeyboardListener.holdingShift) {
				// showTooltip(card.getName() + " at " + card.getImgUrl());
				showTooltip(target.getName() + " at (" + (source.getAbsoluteLeft() - Cardpanda.canvas.getAbsoluteLeft()) + ", "
						+ (source.getAbsoluteTop() - Cardpanda.canvas.getAbsoluteTop()) + ")");
			} else {
				showTooltip(target.getName());
			}
		}
	}

	public void onMouseLeave(Widget source) {
		tip.setVisible(false);
	}

	private void showTooltip(String cardName) {
		tip.setVisible(true);
		tip.fadeInTooltip(200);
		tip.setText(cardName);
		DOM.setStyleAttribute(tip.getElement(), "opacity", "0.0");
		DOM.setStyleAttribute(tip.getElement(), "filter", "alpha(opacity=0)");
	}
}